package com.neusoft.neuiotms.dcam.fixed.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcam.common.model.Location;
import com.neusoft.neuiotms.dcam.common.repository.LocationRepository;
import com.neusoft.neuiotms.dcam.fixed.dto.StorehouseDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Storehouse;
import com.neusoft.neuiotms.dcam.fixed.repository.StorehouseRepository;

@Component
public class StorehouseConverter extends AbstractConverter<Storehouse, StorehouseDTO> {

    @Autowired
    private StorehouseRepository storehouseRepository;
    @Autowired
    private LocationRepository locationRepository;

    @Override
    public Storehouse toModel(final StorehouseDTO dto) {
        final Storehouse model;
        if (dto.isNew()) {
            model = new Storehouse();
        } else {
            model = this.storehouseRepository.getOne(dto.getId());
        }

        model.setName(dto.getName());
        // 位置
        final Location location = this.locationRepository.findByCode(dto.getLocationCode());
        if (location != null) {
            model.setLocation(location);
        }

        model.setStatus(dto.getStatus());
        model.setCreateTime(dto.getCreateTime());
        model.setUpdateTime(dto.getUpdateTime());
        return model;
    }

    @Override
    public StorehouseDTO toDTO(final Storehouse model, final boolean forListView) {
        final StorehouseDTO dto = new StorehouseDTO();

        dto.setId(model.getId());
        dto.setName(model.getName());
        if (model.getLocation() != null) {
            dto.setLocationCode(model.getLocation().getCode());
            dto.setLocationName(model.getLocation().getName());
        }
        dto.setCreateTime(model.getCreateTime());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setStatus(model.getStatus());

        return dto;
    }

}
